package com.dreamlike.demo.HttpUtil.Core.ReuqestBodyHandler;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.dreamlike.demo.HttpUtil.Core.HttpDefinition;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class JsonRequestBodyHandler implements StringRequestBodyHandler {
    private static final ObjectMapper objectMapper= new ObjectMapper();



    public interface JsonGenerator {
        String generate(Object o);
    }

    private JsonGenerator jsonGenerator;

    public JsonRequestBodyHandler() {
        jsonGenerator = (o) -> {
            try {
                return objectMapper.writeValueAsString(o);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return null;
        };
    }

    public JsonRequestBodyHandler(JsonGenerator jsonGenerator) {
        this.jsonGenerator = jsonGenerator;
    }
    @Override
    public String trans(HttpDefinition httpDefinition, Object[] args) {
        if (httpDefinition.getRequestBodyIndex() == HttpDefinition.DEFAULT_REQUEST_BODY_INDEX){
            Map<String, List<String>> params = httpDefinition.getParamRecord()
                    .entrySet()
                    .stream()
                    .collect(Collectors.toMap(Map.Entry::getValue, e -> paramToList(e, args), this::mergeList));
            return jsonGenerator.generate(params);
        }
        return jsonGenerator.generate(args[httpDefinition.getRequestBodyIndex()]);
    }
    public List<String> paramToList(Map.Entry<Integer,String> entry,Object[] args){
        ArrayList<String> list = new ArrayList<>();
        list.add(args[entry.getKey()].toString());
        return list;
    }
    public List<String> mergeList(List<String> l1,List<String> l2){
        l1.addAll(l2);
        return l1;
    }

}
